package com.example.javaow.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.javaow.domain.entity.DeviceCommandLog;
import com.example.javaow.mapper.DeviceCommandLogMapper;
import com.example.javaow.service.DeviceCommandLogService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

/**
 * 指令发送日志服务实现类
 */
@Service
@RequiredArgsConstructor
public class DeviceCommandLogServiceImpl extends ServiceImpl<DeviceCommandLogMapper, DeviceCommandLog> implements DeviceCommandLogService {

    private final DeviceCommandLogMapper deviceCommandLogMapper;

    @Override
    public IPage<DeviceCommandLog> getByConditions(int pageNum, int pageSize,
                                                   Integer groupAddress, Integer deviceAddress) {
        // 创建分页对象
        IPage<DeviceCommandLog> page = new Page<>(pageNum, pageSize);

        // 构建查询条件
        LambdaQueryWrapper<DeviceCommandLog> wrapper = new LambdaQueryWrapper<>();

        // 分组地址（精确匹配）
        if (groupAddress != null) {
            wrapper.eq(DeviceCommandLog::getGroupAddress, groupAddress);
        }

        // 设备地址（精确匹配）
        if (deviceAddress != null) {
            wrapper.eq(DeviceCommandLog::getDeviceAddress, deviceAddress);
        }

        // 按发送时间倒序排列
        wrapper.orderByDesc(DeviceCommandLog::getSendTime);

        // 执行查询
        return deviceCommandLogMapper.selectPage(page, wrapper);
    }

    @Override
    public boolean addDeviceCommandLog(DeviceCommandLog deviceCommandLog) {
        return this.save(deviceCommandLog);
    }
}
